using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ArrivalInspection;
using RBAC.Write.Api.Infrastructure.Storage;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Application.Handler.ArrivalInspection
{
    /// <summary>
    /// 上传到货检验附件 处理器（仅负责把文件存储到对象存储，返回路径）
    /// </summary>
    public class UploadArrivalInspectionAttachmentCommandHandler : IRequestHandler<UploadArrivalInspectionAttachmentCommand, APIResult<string>>
    {
        private readonly IObjectStorage _storage;
        private readonly ILogger<UploadArrivalInspectionAttachmentCommandHandler> _logger;
        private readonly IConfiguration _config;

        public UploadArrivalInspectionAttachmentCommandHandler(IObjectStorage storage, ILogger<UploadArrivalInspectionAttachmentCommandHandler> logger, IConfiguration config)
        {
            _storage = storage;
            _logger = logger;
            _config = config;
        }

        public async Task<APIResult<string>> Handle(UploadArrivalInspectionAttachmentCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<string>();
            try
            {
                if (request.FileBytes == null || request.FileBytes.Length == 0)
                {
                    return new APIResult<string> { Code = APIEnums.Fail, Msg = "文件为空", Data = string.Empty };
                }
                var ext = Path.GetExtension(request.FileName ?? string.Empty);
                var bucket = _config["Minio:Bucket"] ?? "erp-files";
                var objectName = $"arrival-inspection/uploads/{DateTime.UtcNow:yyyy/MM/dd}/{Guid.NewGuid():N}{ext}";

                await using var ms = new MemoryStream(request.FileBytes);
                var storedPath = await _storage.UploadAsync(bucket, objectName, ms, ms.Length, NormalizeContentType(request.ContentType, ext), cancellationToken);

                res.Code = APIEnums.Success;
                res.Msg = "上传成功";
                res.Data = storedPath;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传到货检验附件异常: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "上传到货检验附件异常";
                res.Data = string.Empty;
            }
            return res;
        }

        private static string NormalizeContentType(string contentType, string ext)
        {
            if (!string.IsNullOrWhiteSpace(contentType)) return contentType;
            return ext.ToLowerInvariant() switch
            {
                ".pdf" => "application/pdf",
                ".doc" => "application/msword",
                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                ".xml" => "application/xml",
                ".ofd" => "application/octet-stream",
                _ => "application/octet-stream"
            };
        }
    }
}
